<template>
    <AdminSkeleton>
        <template #header>
            <div class="params-form">
                <el-form :model="paramsForm" label-width="auto" :rules="rules" ref="formRef">
                    <el-form-item label="开始日期" size="small" prop="begindate">
                        <el-date-picker width="70%" size="small" v-model="paramsForm.begindate" type="date" 
                            placeholder="请选择日期"
                            format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
                    </el-form-item>
                    <el-form-item label="结束日期" size="small" prop="enddate"> 
                        <el-date-picker width="70%" size="small" v-model="paramsForm.enddate" type="date"
                            placeholder="请选择日期" 
                            format="YYYY/MM/DD" value-format="YYYY-MM-DD" :value-on-clear="''" />
                    </el-form-item>
                    <el-form-item label="线路:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['',undefined, null]">
                            <el-select v-model="paramsForm.lines" 
                                clearable
                                placeholder="可留空" size="small" style="width: 150px"
                                multiple
                                collapse-tags
                                collapse-tags-tooltip                                
                                @change="changeLines"  
                                @visible-change="getLines"                      
                            >
                                <template #header>
                                    <el-checkbox
                                        v-model="lineCheckAll"
                                        :indeterminate="lineIndeterminate"
                                        @change="lineHandleCheckAll"
                                    >
                                       全选
                                    </el-checkbox>
                                </template>
                                <el-option v-for="item in linesAndStationsArr" :label="item.label" :value="item.value" :key="item.value"/>
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="站点:" size="small">
                        <el-config-provider :value-on-clear="''" :empty-values="['',undefined, null]">
                            <el-select v-model="paramsForm.stations" 
                                multiple
                                clearable
                                collapse-tags
                                collapse-tags-tooltip
                                placeholder="可留空" size="small" style="width: 150px"
                                @change="changeStations"                      
                            >
                            <template #header>
                                    <el-checkbox
                                        v-model="stationCheckAll"
                                        :indeterminate="stationIndeterminate"
                                        @change="stationHandleCheckAll"
                                    >
                                       全选
                                    </el-checkbox>
                                </template>
                                <el-option v-for="item in stationsArr" :label="item.label" :value="item.value" :key="item.value"/>
                            </el-select>
                        </el-config-provider>
                    </el-form-item>
                    <el-form-item label="描述:" size="small">
                        <el-input v-model="paramsForm.desc" size="small" style="width: 100px"/>
                    </el-form-item>
                    <el-form-item size="small">
                            <el-checkbox v-model="paramsForm.isxf" label="只查看消防检测设备" size="small" />
                        </el-form-item>
                    <el-form-item>
                        <el-button type="primary" size="small" @click="getMcsList(paramsForm)"
                        :loading = "loading">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </template >
        <template #control>
            <Control :downloadBoxShow="downloadBoxShow" :permObj="permObj" @showDownload="showDownloadBox"
                @downloadExcelPaging="downloadExcelPaging(newDatasArr, 'dataTable', '主控设备记录')"
                @downloadExcelAll="downloadExcelAll(datasArr, '主控设备记录')">
            </Control>
            <Paging :dataLength="datasLength" :countPage="countPage" :btnDisabledObj="btnDisabledObj"
                v-model:firstPage="firstPage" v-model:pageSize="pageSize" @toNext="nextPage(firstPage)"
                @toLast="lastPage(firstPage)" @toFirst="toFirstPage" @toEnd="toEndPage" @toSpecify="toSpecifyPage"
                @changePsize="changePageSize">
            </Paging>
        </template>
        <template #content>
            <el-table :data="newDatasArr" style="width: 100%" v-loading="loading" id="dataTable"
            >
                <el-table-column fixed prop="CODE" label="主控设备编码" width="150" />
                <el-table-column fixed prop="REPRESENT" label="描述" width="150" />
                <el-table-column prop="LINE" label="线路" width="60" />
                <el-table-column prop="STATION" label="站点" width="120" />
                <el-table-column prop="MAJOR" label="专业" width="60" />
                <el-table-column prop="STATUS" label="状态" width="60" />                
                <el-table-column prop="EVENTTIME" label="发生时间" width="180">
                    <template #default="{ row }">
                        {{ dateFormatTimeStamp(row.EVENTTIME) }}
                    </template>
                </el-table-column>
                <el-table-column prop="ACTION" label="动作" width="120" />
                <el-table-column prop="DEVICEID" label="消防检测设备编码" width="170" />
            </el-table>
        </template>
    </AdminSkeleton>
</template>

<script setup>
import { ref , reactive } from 'vue'
import AdminSkeleton from '@/components/AdminSkeleton.vue'
import Control from '@/components/Control.vue'
import Paging from '@/components/Paging.vue'
import { getLinesInfo } from '@/utils/xfjcApi/device'
import { xfjcStore } from '@/stores/jcStore'
import { dateFormatTimeStamp, dateFormat } from '@/utils/dateFormat'
import { msgOpen } from '@/utils/msg'
import { exportClickFromTableId, exportClickFromDatas } from '@/utils/downloadExcel'
import { paging } from '@/utils/paging'
import { getMcsListInfo } from '@/utils/xfjcApi/mcsList'

let useJcStore = xfjcStore()

//权限对象--用于控制按钮显示
const permObj = {
    add: { name: 'mcsList', type: 'add' },
    update: { name: 'mcsList', type: 'update' },
    delete: { name: 'mcsList', type: 'delete' }
}

const {
    datasArr,
    datasLength,
    firstPage,
    pageSize,
    countPage,
    newDatasArr,
    btnDisabledObj,
    pagingPreprocessing,
    nextPage,
    lastPage,
    toFirstPage,
    toEndPage,
    toSpecifyPage,
    changePageSize
} = paging() //分页

//表格loading
let loading = ref(false)

//查询参数请求对象
let paramsForm = reactive({
    begindate: '',
    enddate: '',
    lines:[],
    stations:[],
    isxf:false,
    desc:""
})


//参数值
//线路、站点
let linesAndStationsArr = ref([])
let lineCheckAll = ref(false)
let lineIndeterminate = ref(false) //设置不确定状态，仅负责样式控制
let stationsArr = ref([])
let stationCheckAll = ref(false)
let stationIndeterminate = ref(false)

/**
 * location转换为树形
 * @param {Array} arr workType 原数组对象 
 */
 const locationToTree = (arr)=>{
    let line = []
    // 先把线路拿出来
    arr.forEach(item => {
        if(item.AREATYPE === '线路'){
            let lineObj = {
                label: item.DESCRIPTION,
                value: item.LOCATION,
                children: []
            }
            line.push(lineObj)
        }       
    })
    // 再把站点拿出来
    line.forEach(item => {
        arr.forEach(item1 => {
            if(item.value === item1.CUST_LINENUM && item1.AREATYPE !== '线路'){
                let stationObj = {
                    label: item1.DESCRIPTION,
                    value: item1.LOCATION,
                    parent: item.value
                }
                item.children.push(stationObj)
            }
        })
    })
    // console.log(line)
    return line
}

//获取线路站点数据
const getLines = async () => {
 //获取数据
    if(!useJcStore.linesInfo.length){
        let lines = await getLinesInfo()
        if(lines.status){
            linesAndStationsArr.value = locationToTree(lines.resDatas.lines)            
            useJcStore.setLinesInfo(linesAndStationsArr.value)
        }
    }else{
        linesAndStationsArr.value = useJcStore.linesInfo
    }  
}

/**
 * 改变线路联动站点
 * @param val 选中的线路值
 */
const changeLines = (val) => {
    // console.log(val)
    // console.log(typeof val)
    // console.log(Array.isArray(val))    
    //#region  
    //单选   
    if(typeof val === 'string'){
        linesAndStationsArr.value.forEach(item => {
            // console.log(item)            
            if(item.value === val) stationsArr.value =  item.children
        }) 
    }
    //多选 el-select组件多选后使用typeof判断为object，需要使用Array.isArray()才能判断为数组
    if(Array.isArray(val)){
        //每次改变线路时，都要把站点清空
        paramsForm.stations = []
        stationCheckAll.value = false
        stationIndeterminate.value = false
        if(val.length === 1){
            //取消全选
            if(linesAndStationsArr.value.length && val.length !== linesAndStationsArr.value.length) {
                lineCheckAll.value = false
                lineIndeterminate.value = true
            }
            linesAndStationsArr.value.forEach(item => {
                // console.log(item)            
                if(item.value === val[0]) stationsArr.value =  item.children
            })        
        }
        else if(val.length === 0){
            stationsArr.value = [] 
            stationCheckAll.value = false
            stationIndeterminate.value = false
            lineCheckAll.value = false
            lineIndeterminate.value = false
        }  
        else if(val.length > 1){
            // 当val长度大于1切等于线路数组长度时，全选勾选
            if(val.length === linesAndStationsArr.value.length){
                lineCheckAll.value = true 
                lineIndeterminate.value = false
            }else{
                lineCheckAll.value = false
                lineIndeterminate.value = true
            }
            let staArrss = []
            // 当val长度大于1时，获取站点
            for(let i = 0; i < val.length; i++){
                let staArrs = []
                for(let j = 0; j < linesAndStationsArr.value.length; j++){
                    let staArr = []
                    if(linesAndStationsArr.value[j].value === val[i]){
                        staArr.push(...linesAndStationsArr.value[j].children)   
                        staArrs.push(...staArr)                 
                    }                
                }             
                staArrss.push(...staArrs)                               
            }
            stationsArr.value = staArrss
        }  
    }  
    //#endregion
}

//线路全选
const lineHandleCheckAll = (val) => {
    lineIndeterminate.value = false
    if (val) {
        paramsForm.lines = linesAndStationsArr.value.map((_) => _.value)
        //需要调用changeLines方法，否则会出现选中的线路没有站点的情况
        changeLines(paramsForm.lines) 
    } else {
        paramsForm.lines = []
        //需要调用changeLines方法，否则会出现不选线路后站点仍存在的情况
        changeLines(paramsForm.lines) 
    } 
}

/**
 * 站点变更
 * @param val 选中的站点值
 */
const changeStations = (val) => {
    if(Array.isArray(val)){
        if(val.length === 1){
            //取消全选
            if(stationsArr.value.length && val.length !== stationsArr.value.length) {
                stationCheckAll.value = false
                stationIndeterminate.value = true
            } 
        }
        else if(val.length === 0){
            stationCheckAll.value = false
            stationIndeterminate.value = false
        }
        else if(val.length > 1){
            // 当val长度大于1切等于站点数组长度时，全选勾选
            if(val.length === stationsArr.value.length){
                stationCheckAll.value = true
                stationIndeterminate.value = false  
            } else{
                stationCheckAll.value = false
                stationIndeterminate.value = true
            }
        }
    }
}

/**
 * 站点全选
 * @param val 站点全选值
 */
const stationHandleCheckAll = (val) => {
    stationIndeterminate.value = false
    if (val) {
        paramsForm.stations = stationsArr.value.map((_) => _.value)
    } else {
        paramsForm.stations = []
    }
}

let formRef = ref(null)
//表单校验
const rules = reactive({
    begindate: [
        { required: true, message: '请选择开始日期', trigger: 'blur' },
    ],
    enddate: [
        { required: true, message: '请选择结束日期', trigger: 'blur' },
    ],
    // line: [
    //     { required: true, message: '请选择线路', trigger: 'blur' },
    // ],
})

/**
 * 查询mcsList
 * @param form 请求参数对象
 */
const getMcsList = (form)=>{
    // console.log(form)
    formRef.value.validate(async (valid) => {
        if (!valid) {
            return false
        } else {
            if (form.begindate > form.enddate) {
                msgOpen("开始日期不能大于结束日期！")
                return false
            }
            loading.value = true
            let res = await getMcsListInfo(form)
            // console.log(res)
            pagingPreprocessing(res.resDatas.mcsListInfo) //分页前置处理
            loading.value = false
        }
    })
}


//下载
//#region 
let downloadBoxShow = ref(false) //展示下载框状态
const showDownloadBox = () => {
    downloadBoxShow.value = !downloadBoxShow.value
}
/** 
 * 下载当前页
 * @param {Array} data 导出的数据数组对象
 * @param {String} tableId table标签的ID
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelPaging = (data, tableId, fileName) => {
    data.length ? exportClickFromTableId(tableId, fileName) : msgOpen("无数据可供下载，请先查询数据")
}
/**
 * 下载全部
 * @param {Array} data 导出的数据数组对象(未进行分页)
 * @param {String} fileName 需要命名的文件名
 */
const downloadExcelAll = (data, fileName) => {
    data?.forEach(item=>{
        // console.log(item)
        item.EVENTTIME = dateFormatTimeStamp(item.EVENTTIME)
        // console.log(item)
    })
    if (data.length) {
        let newData = JSON.parse(JSON.stringify(data)) //深拷贝        
        exportClickFromDatas(newData, fileName)
    } else {
        msgOpen("无数据可供下载，请先查询数据")
    }
}
//#endregion

</script>

<style lang="less" scoped>
.params-form{
    height: 100%;
    width: 100%;
    .el-form{
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        .el-form-item{
            margin-bottom: 0;
            margin-right: .3125rem;
        }
    }    
}
.el-table{
    height: 95%;
}
</style>